const { BrowserWindow, Menu } = require('electron').remote;
const { remote, ipcRenderer } = require('electron');
const curWin = remote.getCurrentWindow();
const path = require('path');
const fs = require('fs');
const util = require('../../libs/util.js');
new Vue({
  el: document.getElementById("root"),
  data() {
    return {
      projectJson: {},
      onlyProject: {},
      onlyApi: {
        name: '',
        url: '',
        type: [],
        template: {},
        javascript: ''
      },
      reqAddress: '',
      showApiDetail: false,
      projectName: '',
      apis: [],
      rules: {
        projectName: [
          { required: true, message: '请输入项目名', trigger: 'blur' }
        ],
        host: [
          { required: true, message: '请输入主机名', trigger: 'blur' }
        ],
        port: [
          { required: true, message: '请输入端口', trigger: 'blur' }
        ],
        baseUrl: [
          { required: true, message: '请输入请求前缀', trigger: 'blur' }
        ]
      },
      editors: {
        obj: null,  //保存editor对象
        input: {},  //存放输入的
        result: {}  //存放运行后的结果
      },
      currentCodeMode: 'application/json',   //设置当前所在的代码编写环境
      currentMenuIndex: 0   //当前左边导航菜单选中的第几个
    }
  },
  watch: {
    currentCodeMode(v) {
      this.editors.obj.setOption("mode", v);
      this.handleSelect(this.currentMenuIndex);
    }
  },
  created() {
    ipcRenderer.on('project', (event, args) => {
      this.projectName = args;
      fs.readFile(path.resolve("/data-mock", "projects", `${this.projectName}`, `${this.projectName}.json`), {encoding: 'utf8'}, (err, data) => {
        if (err) throw err;
        const json = JSON.parse(data);
        this.apis = this.apis.concat(Object.values(json.mocks.string)).concat(json.mocks.regx);
        this.projectJson = json;
        this.onlyProject = {
          projectName: json.projectName,
          host: json.host,
          port: json.port,
          baseUrl: json.baseUrl
        };
      })
    });
    ipcRenderer.on('pushApi', (event, args) => {
      this.apis.push(args);
      if (args.isRegx) {
        this.projectJson.mocks.regx.push(args);
      } else {
        this.projectJson.mocks.string[args.url] = args;
      }
    });
    const template = [
      {
        label: '文件',
        submenu: [
          { label: "退出", role: 'quit' }
        ]
      },
      {
        label: "帮助",
        submenu: [
          {
            label: '规则实例',
            click: () => {
              let win = new BrowserWindow({
                width: 1200,
                height: 800,
                webPreferences: {
                  nodeIntegration: true,
                  webSecurity: false
                },
                icon: './favicon.ico',
                autoHideMenuBar: true
              });
              win.on('closed', () => win = null );
              win.loadFile('./views/pages/doc/index.html');
            }
          },
          {
            label: '关于软件',
            click: () => {
              let win = new BrowserWindow({
                width: 300,
                height: 230,
                webPreferences: {
                  nodeIntegration: true,
                  webSecurity: false
                },
                icon: './favicon.ico',
                autoHideMenuBar: true,
                resizable: false,
                minimizable: false
              });
              win.on('closed', () => win = null );
              win.loadFile('./views/pages/about/about.html');
            }
          }
        ]
      }
    ];

    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  },
  mounted() {
    const that = this;
    this.editors.obj = CodeMirror.fromTextArea(document.getElementById("json_editor_input"), {
      lineNumbers: true,
      mode: that.currentCodeMode,
      gutters: ['CodeMirror-lint-markers'],
      lint: true
    });
  },
  methods: {
    handleCommand(command) {
      const that = this;
      if (command === 'switchProject') {
        let win = new BrowserWindow({
          width: 400,
          height: 600,
          center: true,
          icon: './favicon.ico',
          webPreferences: {
            nodeIntegration: true,
            webviewTag: true
          },
          autoHideMenuBar: true,
          resizable: false,
          minimizable: false
        });

        // 加载index.html文件
        win.loadFile("./views/pages/project-list/index.html");
        win.webContents.on('did-finish-load', () => {
          curWin.close();
        })
      } else if (command === 'createApi') {
        let win = new BrowserWindow({
          width: 400,
          height: 340,
          center: true,
          icon: './favicon.ico',
          webPreferences: {
            nodeIntegration: true,
            webviewTag: true
          },
          autoHideMenuBar: true,
          resizable: false,
          minimizable: false
        });

        // 加载index.html文件
        win.loadFile("./views/pages/create-api/index.html");
        win.on("closed", () => win = null );
        win.webContents.on('did-finish-load', () => {
          win.webContents.send('projectDetailWin-createApiWin', {projectName: this.projectName, projectDetailWinId: curWin.id});
        })
      } else if (command === 'extendGlobleJs') {

      }
    },
    handleSelect(key, keyPath) {
      this.currentMenuIndex = key;
      this.onlyApi = this.apis[key];
      this.reqAddress = `http://${this.onlyProject.host}:${this.onlyProject.port}${this.onlyProject.baseUrl}${this.onlyApi.url}`;
      if (this.currentCodeMode === "javascript") this.editors.obj.setValue(this.onlyApi.javascript);
      else this.editors.obj.setValue(JSON.stringify(this.onlyApi.template, null, 4));
      setTimeout(() => {
        this.editors.obj.refresh()
      }, 1)
      this.showApiDetail = true;
    },
    modifyProject() {
      this.$refs.onlyProject.validate((valid) => {
        if (valid) {
          Object.assign(this.projectJson, this.onlyProject);
          const filePath = path.resolve("/data-mock", "projects", this.projectName, `${this.projectName}.json`);
          fs.writeFileSync(filePath, JSON.stringify(this.projectJson, null, 4));
          if (this.projectName !== this.projectJson.projectName) {
            //修改 目录名  文件名
            fs.renameSync(path.resolve("/data-mock", "projects", `${this.projectName}`, `${this.projectName}.json`), path.join("root", "projects", `${this.projectName}`, `${this.projectJson.projectName}.json`))
            fs.renameSync(path.resolve("/data-mock", "projects", `${this.projectName}`), path.join("root", "projects", `${this.projectJson.projectName}`));
            this.projectName = this.projectJson.projectName;
          }
          this.$message.success("修改成功");
        } else {
          this.$message.warning("数据不正确");
          return false;
        }
      });
    },
    delApi() {
      this.$confirm(`确定删除接口[${this.onlyApi.name}]吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const i = this.apis.indexOf(this.onlyApi);
        if (i > -1) this.apis.splice(i, 1);
        if (this.onlyApi.isRegx) {
          for (let i = 0, len = this.projectJson.mocks.regx.length; i < len; i++) {
            if (this.onlyApi.url === this.projectJson.mocks.regx[i].url) {
              this.projectJson.mocks.regx.splice(i, 1);
              break;
            }
          }
        } else {
          this.projectJson.mocks.string[this.onlyApi.url] = undefined;
        }
        const filePath = path.resolve("/data-mock", "projects", this.projectName, `${this.projectName}.json`);
        fs.writeFileSync(filePath, JSON.stringify(this.projectJson, null, 4));
        this.showApiDetail = false;
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      });
    },
    test() {
      const template = this.editors.obj.getValue();// util.jsonStrFormat(document.getElementById("json_editor_input").innerText);
      // console.log(template)
      const js = this.onlyApi.javascript;
      if (template.trim() !== "") {//console.log(template)
        try {
          if (js) eval(js);
          const result = Mock.mock(JSON.parse(template)); //eval('(' + template + ')')
          document.getElementById("json_editor_result").innerHTML = util.objToJsonStrShow(result);//this.editors.obj.setValue(JSON.stringify(result, null, 4));
        } catch(e) {
          document.getElementById("json_editor_result").innerHTML = `<span style='color:red;'>${e}</span>`;
        }
      }
    },
    save() {
      const template = this.editors.obj.getValue();//util.jsonStrFormat(document.getElementById("json_editor_input").innerText);
      if (this.currentCodeMode === "javascript") this.onlyApi.javascript = template;
      else this.onlyApi.template = JSON.parse(template);//eval('(' + template + ')');
      // console.log(template)
      if (this.onlyApi.isRegx) {
        for (let i = 0, len = this.projectJson.mocks.regx.length; i < len; i++) {
          if (this.onlyApi.url === this.projectJson.mocks.regx[i].url) {
            this.projectJson.mocks.regx.splice(i, 1, this.onlyApi);
            break;
          }
        }
      } else {
        this.projectJson.mocks.string[this.onlyApi.url] = this.onlyApi;
      }
      const filePath = path.resolve("/data-mock", "projects", this.projectName, `${this.projectName}.json`);
      fs.writeFileSync(filePath, JSON.stringify(this.projectJson, null, 4));
      this.$message.success("保存成功");
    },
    startServer() {
      let win = new BrowserWindow({
        width: 800,
        height: 400,
        webPreferences: {
          nodeIntegration: true,
          webSecurity: false
        },
        autoHideMenuBar: true
      });
      win.on('closed', () => win = null );
      win.loadFile('./template/console.html');
      // win.webContents.openDevTools()

      win.webContents.on('did-finish-load', () => {
        win.webContents.send('projectName', this.projectName);
      })
    }
  }
});
